package com.sh.demo.qa.module.qa.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.sh.demo.qa.base.DynamicSpecifications;
import com.sh.demo.qa.base.SearchFilter;
import com.sh.demo.qa.base.SearchFilter.Operator;
import com.sh.demo.qa.module.qa.dao.QuestionDao;
import com.sh.demo.qa.module.qa.entity.Question;

@Service("questionService")
public class QuestionServiceImpl implements QuestionService{
	
	protected final static Logger logger = LoggerFactory.getLogger(QuestionServiceImpl.class);
	
	@Autowired
	private QuestionDao questionDao;
	
	/**
	 * 分页查询
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public Page<Question> getListByPage(int currentPage, int pageSize, String sortType, Date startTime, Date endTime, Question info) {
		
		PageRequest pageRequest = buildPageRequest(currentPage, pageSize, sortType);
		Specification<Question> spec = buildSpecification(startTime, endTime, info);
		return questionDao.findAll(spec, pageRequest);
	}
	
	/**
	 * 创建分页请求
	 */
	private PageRequest buildPageRequest(int currentPage, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("title".equals(sortType)) {
			sort = new Sort(Direction.ASC, "title");
		}
		return new PageRequest(currentPage - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合
	 */
	private Specification<Question> buildSpecification(Date startTime, Date endTime, Question info) {
		
		List<SearchFilter> filters = new ArrayList<SearchFilter>();
		
		// 标题过滤
		String title = info.getTitle();
		if(title != null && !title.trim().equals("")){
			SearchFilter titleFilter = new SearchFilter("title", Operator.LIKE, title);
			filters.add(titleFilter);
		}
		
		// 时间过滤
		if(startTime != null){
			SearchFilter startTimeFilter = new SearchFilter("createtime", Operator.GTE, startTime);
			filters.add(startTimeFilter);
		}
		if(endTime != null){
			SearchFilter endTimeFilter = new SearchFilter("createtime", Operator.LTE, endTime);
			filters.add(endTimeFilter);
		}
		
		Specification<Question> spec = DynamicSpecifications.bySearchFilter(filters, Question.class);
		return spec;
	}


	@Transactional(propagation=Propagation.REQUIRED)
	public boolean addQuestion(Question info){
		
		try {
			info.setCreatetime(new Date());
			questionDao.save(info);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

}
